﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB;
using System.Configuration;

namespace Hands.Unit.DataBaseHelper
{
    public class MongoHelper : IOperation
    {
        private static string mongoConnectionString = null;

        static MongoHelper()
        {
            mongoConnectionString = ConfigurationManager.AppSettings["mongodb"];
        }

        private Mongo instance = null;
        private IMongoDatabase database = null;

        public MongoHelper(string databaseName)
        {
            instance = new Mongo(mongoConnectionString);
            database = instance.GetDatabase(databaseName);

        }

        private IMongoCollection<T> getCollection<T>() where T : class
        {
            return database.GetCollection<T>();
        }

        #region IOperation 成员

        public void delete<T>(T module) where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            collection.Remove(module);
        }

        public void insert<T>(T module) where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            collection.Insert(module);
        }

        public void insert<T>(IEnumerable<T> modules) where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            collection.Insert<T>(modules);
        }


        public T selectOne<T>(string jsonQueryConditions) where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            return collection.FindOne(jsonQueryConditions);
        }

        public IEnumerable<T> select<T>(string jsonQueryConditions) where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            ICursor<T> results = collection.Find(jsonQueryConditions);
            return results.Documents;
        }

        public IEnumerable<T> select<T>() where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            ICursor<T> results = collection.FindAll();
            return results.Documents;
        }

        public void update<T>(T module) where T : class
        {
            IMongoCollection<T> collection = getCollection<T>();
            collection.Save(module);
        }

        #endregion
    }
}
